# -*- coding: utf-8 -*-
from datetime import datetime
import re
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from apps.news.models import RecordImage
from apps.news.services.compiler import Compiler
from core.libs.translit import slugify
from core.models import Category
from ..models import Record
from ..forms import RecordForm
from core.decorators import render
from core.enum import REQUEST_POST

@csrf_exempt
@render("admin/news/preview.html")
def preview(request):

    story = request.REQUEST.get('story')
    record = Record(
        title = '',
        story = story,
        compiled_story = ''
    )

    compiler = Compiler()
    compiler.compile(record)

    return {
        'story': record.compiled_story
    }

@render("admin/news/edit.html")
def edit(request, pk=None):

    if pk:
        record = Record.objects.get(pk=pk)

    if request.method == REQUEST_POST:

        data = request.POST.copy()

        form = RecordForm(data)
        if form.is_valid():
            if pk:
                record.title = form.cleaned_data.get('title', '')
                record.category = form.cleaned_data['category']
                record.publish_date = form.cleaned_data.get('publish_date', '')
                record.author = form.cleaned_data.get('author', '')
                record.story = form.cleaned_data.get('story', '')
                record.status = form.cleaned_data.get('status', '')
                record.url = form.cleaned_data.get('url')
                if not len(record.url):
                    record.url = "%s" % slugify(data.get('title'))
                record.meta_description = form.cleaned_data.get('meta_description', '').strip()
                record.meta_keywords = form.cleaned_data.get('meta_keywords', '').strip()
                record.views = form.cleaned_data.get('views', '')
                record.rating = form.cleaned_data.get('rating', '')
                record.save()
                
            else:
                record = Record.objects.create(
                    title = form.cleaned_data.get('title', ''),
                    category = form.cleaned_data.get('category'),
                    publish_date = form.cleaned_data.get('publish_date', ''),
                    author = form.cleaned_data.get('author', ''),
                    story = form.cleaned_data.get('story', ''),
                    status = form.cleaned_data.get('status', ''),
                    url = form.cleaned_data.get('url', ''),
                    meta_description = form.cleaned_data.get('meta_description', '').strip(),
                    meta_keywords = form.cleaned_data.get('meta_keywords', '').strip(),
                    views = form.cleaned_data.get('views', ''),
                    rating = form.cleaned_data.get('rating', '')
                )
                if not len(record.url):
                    record.url = "%s" % slugify(data.get('title'))
                record.save()

            images = RecordImage.objects.filter(
                record = None
            )
            for image in images:
                if image.image in record.story:
                    image.record = record
                    image.save()

            record._compile_story()

            # here update meta
            pattern = re.compile("<[^<]*?>")
            clean_text = pattern.sub('', record.full_story())

            if not data.get('meta_description'):
                record.meta_description = clean_text[:150]

            if not data.get('meta_keywords'):
                p = re.compile(r'\.|\,|\?|\;|\/|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\[|\]|\\|\:|\"|\'|\-|\=|\+|\~|\`')
                keywords = p.sub('', clean_text).split(' ')
                record.meta_keywords = ','.join(keywords[:10])

            record.save()


            messages.success(request, "Новость успешно сохранена")
            return HttpResponseRedirect("/admin/news/record/")
    else:
        if pk:
            if not record.publish_date:
                record.publish_date = datetime.now()

            form = RecordForm(instance=record)
        else:
            form = RecordForm(initial={
                'publish_date': datetime.now()
            })

    return {
        'form': form,
        'record_pk': pk
    }
